/*******************************************************************************
 * Venice Noise Android Application
 * Copyright (C) 2011  Worcester Polytechnic Institute, Wesley Ripley
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; version 2
 * of the License
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 * 
 * If you plan to use or modify any of this code please contact Fabio Carrera (carrera.fabio@gmail.com)
 * Also please attribute any code used in the final product to the developers. 
 * 
 * Author: Wesley Ripley (wripley@wpi.edu) 
 *******************************************************************************/

package org.venicenoise.app;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Environment;
import android.widget.TextView;

/**
 * A class consisting of static utility constants and functions useful
 * across the entire application.
 * 
 * @author Wesley Ripley
 * @version 12/11/2011
 */
public class AppUtil {
	
	/**
	 * The tag to be used when writing to the log from anywhere in the application
	 */
	public final static String LOG_TAG = "VeniceNoiseApp";
	/**
	 * The path to where all files created using this application should be stored
	 */
	public final static String STORAGE_PATH = "/Android/data/org.venicenoise.app/files/";
	
	/**
	 * Whether or not the option too go into field test mode should be available
	 */
	protected final static boolean FIELD_TESTING_OPTION = true;

	/**
	 * A boolean for testing purposes. When FIX_LOCATION is set to true, the location is fixed
	 * to a static value and all submissions are in test mode. For more details see its
	 * usages
	 */
	protected final static boolean FIX_LOCATION = false;
	
	/**
	 * A boolean value for testing purposes. When LOGGING is true, all writing to the log
	 * will be enabled. Otherwise nothing will write to the log
	 */
	protected final static boolean LOGGING = false;
	
	/**
	 * A boolean value for testing purposes. When DELETE_FILES is true, the audio and
	 * photo files will be deleted as soon as they are successfully uploaded
	 */
	protected final static boolean DELETE_FILES = true;
	/**
	 * The current mode of the application. By default is PUBLIC
	 * Change this to TEST if you are doing testing and do not want
	 * the submitted data to end up on the main web page. 
	 */
	protected final static NoiseData.Type MODE = NoiseData.Type.PUBLIC;
	
	/**
	 * Get a string representation of the current version of the application
	 * @param context
	 * 		The Context of the application (usually from the calling Activity)
	 * @return
	 * 		a string representation of the current version of the application
	 */
    public static String getVersionString(Context context)
    {
    	 try {
			PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
			return info.versionName;
		} catch (NameNotFoundException e) {
			//do nothing should always be found
		}
    	return "";
    }
    
    /**
     * Set the version text on the main header for the given activity
     * @param activity
     * 		The activity to set the header for
     */
    public static void setVersionInHeader(Activity activity)
    {
    	TextView version = (TextView)activity.findViewById(R.id.version);
    	if(version != null)
        {
    		version.setText("v"+AppUtil.getVersionString(activity));
        }
    }
    
    /**
     * Get the User Agent string that should be used when interfacing with the web
     * @param context
     * 		The context of the application (usually from the calling Activity)
     * @return
     * 		the User Agent string that should be used when interfacing with the web
     */
    public static String getUserAgentString(Context context)
    {
    	return "VeniceNoiseApp/"+AppUtil.getVersionString(context);
    }
    
    /**
     * Displays a dialog informing the user of an error.
     * @param context
     * 		The context of the application (usually from the calling Activity)
     * @param message
     * 		The error message to display to the user
     */
	public static void showErrorDialog(Context context, String message) {
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setMessage(message)
			   .setTitle(context.getString(R.string.error))
			   .setCancelable(false)
			   .setNeutralButton(context.getString(R.string.ok), new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			               	dialog.dismiss();//when they click okay dismiss the dialog
			           }
			       });
		       
		AlertDialog errorDialog = builder.create();
		errorDialog.show();	
	}
	
	/**
	 * Displays a dialog informing the user of some information
	 * @param context
	 * 		The context of the application (usually from the calling Activity)
	 * @param title
	 * 		The title of the dialog
	 * @param info
	 * 		The information to display
	 */
	public static void showInfoDialog(Context context, String title, String info)
	{
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setMessage(info)
			   .setTitle(title)
			   .setCancelable(false)
			   .setNeutralButton(context.getString(R.string.ok), new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			               	dialog.dismiss();//when they click okay dismiss the dialog
			           }
			       });
		       
		AlertDialog infoDialog = builder.create();
		infoDialog.show();	
	}
	
	/**
	 * Creates a file in external storage
	 * @param context
	 * 		The context of the application (usually from the calling Activity)
	 * @param prefix
	 * 		The prefix of the filename to be created
	 * @param extension
	 * 		The extension for the file (with the ".", Ex ".wav", ".jpg")
	 * @param create
	 * 		Whether the file should be created on disk or not. If true, the actual file
	 * 		will be created. If false a the File object will be created and returned but not
	 * 		wrote to disk
	 * @return
	 * 		The File object representing the newly created file.
	 */
	public static File createFile(Context context, String prefix,String extension,boolean create)
	{
		final File file;
		final Calendar now = Calendar.getInstance();
		final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd_HHmmss");
		final String fileNameSuffix = dateFormat.format(now.getTime());
		//file name format is <prefix><timestamp><extension>
		file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + AppUtil.STORAGE_PATH + prefix+fileNameSuffix+extension);
		file.getParentFile().mkdirs();
		if(create)
		{
	        try {
				file.createNewFile();
			} catch (IOException e) {
				AppUtil.showErrorDialog(context, context.getString(R.string.cannotCreateFile));
				return null;
			}
		}
		return file;
	}
	
	/**
	 * Determines if the given string is empty or null
	 * @param s
	 * 		the string in question
	 * @return
	 * 		true if string is empty or null, false otherwise
	 */
	public static boolean isEmptyOrNull(String s)
	{
		return s == null || s.length() == 0;
	}
	
}
